package com.ydm.myapp001.activity;

import android.content.Context;
import android.graphics.Color;
import android.location.Location;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.ydm.myapp001.R;

public class BaiduMapActivity extends AppCompatActivity {
    private Context mContext = this;
    private MapView mMapView;
    private BaiduMap mBaiduMap;
    private static final int accuracyCircleFillColor = 0xAAFFFF88;
    private static final int accuracyCircleStrokeColor = 0xAA00FF00;
    private MyLocationConfiguration.LocationMode mCurrentMode = MyLocationConfiguration.LocationMode.NORMAL;
    private BitmapDescriptor mCurrentMarker = BitmapDescriptorFactory.fromResource(R.drawable.img_user_location);//定位位置的图片


    //
    public LocationClient mLocationClient = null;
    private MyLocationListener myListener = new MyLocationListener();


    private BDLocation userLocation;


    private Marker mMarkerA;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_baidu_map);

        //获取地图控件引用
        mMapView = (MapView) findViewById(R.id.bmapView);
        mBaiduMap = mMapView.getMap();
        mMapView. showZoomControls(false);//不显示缩放按钮


        /*
        添加绘制点标注
        addMarker();
        */



        //自定义地图定位模式、定位图标、精度圈颜色
        mBaiduMap.setMyLocationConfiguration(new MyLocationConfiguration(mCurrentMode, false, mCurrentMarker, accuracyCircleFillColor, accuracyCircleStrokeColor));
        //开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
        //定位参数配置
        initLocationSdkPara();
    }




    /*
    * 定位sdk中参数设置
    * */
    public void initLocationSdkPara(){
        /****** 初始化LocationClient类 ******/
        //声明LocationClient类
        mLocationClient = new LocationClient(getApplicationContext());
        //注册监听函数
        mLocationClient.registerLocationListener(myListener);


        /****** 配置定位SDK参数 ******/
        LocationClientOption option = new LocationClientOption();
        //可选，设置定位模式，默认高精度
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        /*
        * 可选，设置返回经纬度坐标类型，默认gcj02
        * gcj02：国测局坐标；
        * bd09ll：百度经纬度坐标；
        * bd09：百度墨卡托坐标；
        * 海外地区定位，无需设置坐标类型，统一返回wgs84类型坐标*/
        option.setCoorType("bd09ll");
        /*
        * 可选，设置发起定位请求的间隔，int类型，单位ms
        * 如果设置为0，则代表单次定位，即仅定位一次，默认为0
        * 如果设置非0，需设置1000ms以上才有效
        * */
        option.setScanSpan(1000);
        /*
        * 可选，设置是否使用gps，默认false
        * 使用高精度和仅用设备两种定位模式的，参数必须设置为true
        * */
        option.setOpenGps(true);
        //可选，设置是否当GPS有效时按照1S/1次频率输出GPS结果，默认false
        option.setLocationNotify(true);
        //可选，是否需要地址信息，默认为不需要，即参数为false；如果开发者需要获得当前点的地址信息，此处必须为true
        option.setIsNeedAddress(true);
        //需将配置好的LocationClientOption对象，通过setLocOption方法传递给LocationClient对象使用
        mLocationClient.setLocOption(option);
        //最后，只需发起定位，便能够从BDAbstractLocationListener监听接口中获取定位结果信息
        mLocationClient.start();
    }


    /*
    * 在地图上显示定位
    * */
    private void showUserLocationOnMap() {
        Log.d("YDMLog", "showUserLocation: ");
        //构造定位数据
        MyLocationData locData = new MyLocationData.Builder().accuracy(userLocation.getRadius()).direction(100).latitude(userLocation.getLatitude()).longitude(userLocation.getLongitude()).build();

        //在地图上设置定位数据
        mBaiduMap.setMyLocationData(locData);





        //地图定位图标点击事件监听接口
        BaiduMap.OnMyLocationClickListener listener = new BaiduMap.OnMyLocationClickListener() {
            InfoWindow.OnInfoWindowClickListener listener = null;
            /**
             * 地图定位图标点击事件监听函数
             */
            public boolean onMyLocationClick(){
                //创建InfoWindow展示的view
                Button button = new Button(getApplicationContext());
                button.setBackgroundResource(R.drawable.popup);
                button.setText("您的位置");
                button.setTextColor(Color.BLACK);
                button.setWidth(300);
                listener = new InfoWindow.OnInfoWindowClickListener() {
                    public void onInfoWindowClick() {
                        mBaiduMap.hideInfoWindow();
                    }
                };
                //定义用于显示该InfoWindow的坐标点
                LatLng pt = new LatLng(userLocation.getLatitude(), userLocation.getLongitude());
                //创建InfoWindow , 传入 view， 地理坐标， y 轴偏移量
                InfoWindow mInfoWindow = new InfoWindow(BitmapDescriptorFactory.fromView(button), pt, 0, listener);
                //显示InfoWindow
                mBaiduMap.showInfoWindow(mInfoWindow);

                return true;
            }
        };
        //添加定位图标点击事件监听
        mBaiduMap.setOnMyLocationClickListener(listener);


        //
        LatLng ll = new LatLng(userLocation.getLatitude(),
                userLocation.getLongitude());
        MapStatus.Builder builder = new MapStatus.Builder();
        builder.target(ll).zoom(18.0f);
        mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));

        //停止定位
        mLocationClient.stop();

    }



    public void addMarker(){
        /*************************/
        LatLng point = new LatLng(39.963175, 116.400244);

        //构建Marker图标
        final BitmapDescriptor bitmap = BitmapDescriptorFactory
                .fromResource(R.drawable.img_user_location);

        //构建MarkerOption，用于在地图上添加Marker
        OverlayOptions option = new MarkerOptions()
                .position(point)
                .icon(bitmap);



        //在地图上添加Marker，并显示
        mMarkerA = (Marker) mBaiduMap.addOverlay(option);
        //
        mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            InfoWindow.OnInfoWindowClickListener listener = null;
            @Override
            public boolean onMarkerClick(Marker marker) {
                if (marker == mMarkerA) {
                    //创建InfoWindow展示的view
                    Button button = new Button(getApplicationContext());
                    button.setBackgroundResource(R.drawable.popup);
                    button.setText("您的位置");
                    button.setTextColor(Color.BLACK);
                    button.setWidth(300);
                    listener = new InfoWindow.OnInfoWindowClickListener() {
                        public void onInfoWindowClick() {
                            mBaiduMap.hideInfoWindow();
                        }
                    };
                    //定义用于显示该InfoWindow的坐标点
                    LatLng pt = new LatLng(marker.getPosition().latitude, marker.getPosition().longitude);
                    //创建InfoWindow , 传入 view， 地理坐标， y 轴偏移量
                    InfoWindow mInfoWindow = new InfoWindow(BitmapDescriptorFactory.fromView(button), pt, -47, listener);
                    //显示InfoWindow
                    mBaiduMap.showInfoWindow(mInfoWindow);
                }


                return true;
            }
        });
    }

    public void backTo(View v) {
        finish();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        mMapView.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        mMapView.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        mMapView.onDestroy();
    }


    public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location){
            Log.d("YDMLog", "onReceiveLocation: ");
            //此处的BDLocation为定位结果信息类，通过它的各种get方法可获取定位相关的全部结果
            //以下只列举部分获取经纬度相关（常用）的结果信息
            //更多结果信息获取说明，请参照类参考中BDLocation类中的说明

            double latitude = location.getLatitude();    //获取纬度信息
            double longitude = location.getLongitude();    //获取经度信息
            Log.d("YDMLog", "("+latitude+","+longitude+")");
            float radius = location.getRadius();    //获取定位精度，默认值为0.0f

            String addr = location.getAddrStr();    //获取详细地址信息
            if (addr==null){
                Log.d("YDMLog", "onReceiveLocation: 地址null");
            }
            else {
                Log.d("YDMLog", "onReceiveLocation: "+addr);
            }

            String coorType = location.getCoorType();
            //获取经纬度坐标类型，以LocationClientOption中设置过的坐标类型为准

            int errorCode = location.getLocType();
            //获取定位类型、定位错误返回码，具体信息可参照类参考中BDLocation类中的说明


            //在地图上显示这个定位位置
            userLocation = location;
            showUserLocationOnMap();
        }
    }
}
